<template>
  <!-- 中间表单内容 -->
  <el-row
    :gutter="$attrs.gutter"
    class="form-row-container Fg-tips"
    :class="border?'drawing-border':''"
    :style="{ height: isEdit?height:'' ,marginLeft:0,marginRight:0,...newStyle}"
  >
    <EmptyTips v-if="drawingList.length==0 " />
    <draggable
      :disabled="!isEdit || onlyShow"
      class="Fg-form-draggable"
      :class="flexClass"
      v-model="drawingList"
      :animation="340"
      :style="{minHeight:drawingList.length ==0 && isEdit?'60px':0}"
      group="componentsGroup"
      @start="dragStart"
      @end="dragEnd"
    >
      <template #item="{element: item,index}">
        <el-col
          class="Fg-form-item"
          v-show="!item.isHide || isEdit"
          :class="isEdit ? changClass(item, currentData, formConf) : ''"
          :span="item.__config__.span"
          @click.native.stop="activeFormItem(item,$event )"
        >
          <div class="Fg-form-item--topIcon" v-if="isEdit">
            <svg-icon v-if="item.isHide" :iconClass="item.isHide?'noview':'view'" />
            <i v-if="item.isLock" :class="item.isLock?'el-icon-lock':'el-icon-unlock'" />
          </div>
          <div
            class="Fg-form-item--icon"
            v-if="isEdit && !onlyShowFun(item) && activeId==item.__config__.formId"
          >
            <!-- <MenuButton icon="el-icon-back" @click="toLeft(item, index)" /> -->
            <MenuButton v-if="index>0" icon="el-icon-top" @click="toTop(item, index)" />
            <MenuButton
              v-if="index!==drawingList.length-1"
              icon="el-icon-bottom"
              @click="toBottom(item, index)"
            />
            <MenuButton
              v-if="!item.isLock"
              icon="el-icon-copy-document"
              @click="drawingItemCopy(item)"
            />
            <MenuButton
              v-if="!item.isLock"
              icon="el-icon-delete"
              type="danger"
              @click="drawingItemDelete(item, index)"
            />
          </div>
          <el-config-provider :locale="zhCnC" v-if="['layout','assist'].includes(item.__config__.tagType)">
            <component
              v-model="item.__config__.defaultValue"
              :is="item.__config__.tag"
              v-bind="toCamelCase(deepClone(item))"
              :disabled="item.disabled || formConf.disabled"
              :formConf="formConf"
              :list.sync="item.children"
              :isEdit="isEdit"
              :enabled="enabled"
              :font="newStyle.font"
              :onlyShow="onlyShowFun(item)"
              :border="isEdit"
              @active="activeFormItem"
              @clone="handleClone"
            />
          </el-config-provider>
          <el-form-item
            v-else
            :class="{
              'mask-layer': ((!enabled && item.__config__.tag !== 'form-row-container') ||item.readonly)&&!onlyShowFun(item),
              'mar-bot-none': onlyShow,
            }"
            :label="item.__config__.showLabel ? item.__config__.label : ''"
            :label-width="
              item.__config__.tag == 'form-row-container' ||
              !item.__config__.showLabel
                ? '0px'
                : item.__config__.labelWidth
                ? item.__config__.labelWidth + 'px'
                : ''
            "
            :required="
              item.__config__.required && !item.disabled && !item.readonly && !onlyShowFun(item)
            "
            :rules="formRules({...item,onlyShow:onlyShowFun(item)})"
            :prop="isEdit ? '' : item.__vModel__"
          >
            <template #label>
              <span
                v-if="item.__config__.showLabel"
                :style="newStyle.font"
              >{{item.__config__.label}}</span>
            </template>
            <!-- toCamelCase 需要将所有属性名更改为驼峰命名法，不然无法生效 -->
            <el-config-provider :locale="zhCnC">
              <component
                v-model="item.__config__.defaultValue"
                :is="item.__config__.tag"
                v-bind="toCamelCase(deepClone(item))"
                :disabled="item.disabled || formConf.disabled"
                :formConf="formConf"
                :list.sync="item.children"
                :isEdit="isEdit"
                :enabled="enabled"
                :font="newStyle.font"
                :onlyShow="onlyShowFun(item)"
                @active="activeFormItem"
                @clone="handleClone"
                @validate="validateRow(item)"
              />
            </el-config-provider>
          </el-form-item>
        </el-col>
      </template>
    </draggable>
  </el-row>
</template>

<script>
import draggable from "vuedraggable";
import { deepClone, toCamelCase } from "../../../utils/index";
import {
  createFormItem,
  updateForm,
  changClass,
  formRules,
  handleEvent,
  swapArray,
} from "../../../utils/index";
import MenuButton from "../../../huComponents/MenuButton";
import store from "@/store";
import emitter from '@/utils/eventBus';

import { comMixin } from "../../../utils/comMixins";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

export default {
  mixins: [comMixin],
  name: "form-row-container",
  components: {
    draggable,
    MenuButton,
  },
  props: {
    // 表单属性
    formConf: {
      type: Object,
      default: () => {},
    },
    // 表单列表
    list: {
      type: Array,
      default: () => [],
    },
    __config__: {
      type: Object,
      default: () => {},
    },
    // 是否为编辑模式
    isEdit: {
      type: Boolean,
      default: true,
    },
    // 是否为显示模式
    onlyShow: {
      type: Boolean,
      default: false,
    },
    isPreview: {
      type: Boolean,
      default: false,
    },
    height: {
      type: String,
      default: "",
    },
    enabled: {
      type: Boolean,
      default: false,
    },
    border: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      drawingList: [], // 初始化时默认选中表单组件
      activeData: {}, // 选中值
      formModel: {},
    };
  },

  computed: {
    flexClass() {
      let className = `el-row--flex is-align-${this.$attrs.align} is-justify-${this.$attrs.justify}`;
      return `${this.isEdit ? "drawing-board" : ""} ${
        this.$attrs.type == "flex" ? className : ""
      }`;
    },
    // 当前选中表单组件
    currentData() {
      return store.state.app.activeData;
    },
    activeId() {
      return store.state.app.activeId;
    },
    zhCnC() {
      return zhCn
    }
  },

  watch: {
    // 当前选中的表单项数据
    currentData: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          this.activeData = deepClone(newValue);
          updateForm(this.drawingList, newValue);
        }
      },
    },

    list: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          this.drawingList = newValue;
          // this.drawingList = deepClone(newValue);
          // 当列表中的数据发生变化时，需要同步更改右侧属性
          const currentData = this.drawingList.find(
            (item) =>
              item.__config__.formId == this.activeData?.__config__?.formId
          );
          if (
            JSON.stringify(currentData) !== JSON.stringify(this.currentData)
          ) {
            this.activeFormItem(currentData);
          }
        }
      },
    },
    drawingList: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (JSON.stringify(newValue) !== JSON.stringify(this.list)) {
          this.$emit("update:list", newValue);
        }
      },
    },
  },

  methods: {
    validateRow(item) {
      this.$emit('validate',item);
      emitter.emit('verify', item);
    },
    toCamelCase,
    deepClone,
    changClass,
    formRules,
    handleEvent,
    onlyShowFun(item) {
      return this.onlyShow || item?.onlyShow;
    },

    // 选中某一表单项
    activeFormItem(currentItem, event) {
      // 只有在表单编辑器模式下才执行后续逻辑
      if (!this.isEdit) return;
      event?.stopPropagation();
      // 需要将当前页所有数据渲染完了之后再更新当前选中
      this.$nextTick(() => {
        if (currentItem && !this.isPreview) {
          this.activeData = currentItem;
          store.commit("SET_ACTIVEDATA", currentItem);
          this.$emit("active", currentItem, event);
        }
      });
    },
    // 复制表单项
    drawingItemCopy(item) {
      let clone = deepClone(item);
      clone = createFormItem(clone);
      this.handleClone(clone);
      // this.activeFormItem(clone);
    },
    handleClone(clone) {
      this.drawingList.push(clone);
    },
    // 删除表单项
    drawingItemDelete(item, index) {
      this.drawingList.splice(index, 1);
      if (this.drawingList.length) {
        this.activeFormItem(this.drawingList[0]);
      } else {
        this.activeFormItem({});
      }
    },
    // 开始拖拽
    dragStart(obj) {
      // console.log("开始拖拽", obj);
    },
    // 结束拖拽
    dragEnd(obj) {
      // console.log("结束拖拽", obj);
    },
    // 键盘事件
    handleKeyPress(item, index, event) {
      // 获取按下的键的ASCII码
      const keyCode = event.keyCode || event.which;
      // 输出按键信息
      console.log("Pressed key code:", keyCode);
    },
    // 左移
    toLeft(item, index) {
      console.log("左移:", item, index);
    },
    // 上移
    toTop(item, index) {
      swapArray(this.drawingList, index - 1, index);
    },
    // 下移
    toBottom(item, index) {
      swapArray(this.drawingList, index, index + 1);
    },
  },
};
</script>

<style lang="scss">
.form-row-container {
  overflow: auto;
}
</style>
